from logging import getLogger

import sys

from zope.interface import implements

from twisted.python import usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker, MultiService
from twisted.application import internet

from nevow.appserver import NevowSite

from meercat.job import JobService

from meercat.server.nevow.page import Root



log = getLogger('twisted.plugins.meercat_server_nevow_plugin')

class Options(usage.Options):
    optParameters = [['port', '', 8085, 'The port number to listen on.'],
                     ['zcml', '', None, 'The site.zcml file to use for configuration.'],
                     ['logconfig', '', None, 'Logging configuration file to use'],]
    
    def opt_version(self):
        """Print version information and exit.
        """
        print 'meercat-server 1.0b'
        print '1.0b'
        sys.exit()


class MeercatNevowServiceMaker(object):
    implements(IServiceMaker, IPlugin)
    tapname = "meercat-nevow"
    description = "Run a Meercat administration site"
    options = Options

    def makeService(self, options):
        """
        Construct a TCPServer from a factory defined in myproject.
        """
        
        if options.get('logconfig',None):
            try:
                from logging.config import fileConfig
                fileConfig(options.get('logconfig'))
                
                from twisted.python.log import PythonLoggingObserver
                PythonLoggingObserver().start()
            except Exception, e:
                from traceback import print_tb
                print_tb(sys.exc_info()[2])
                raise e
        
        if options.get('zcml',None):
            log.info('Loading zcml configuration from %s' % (options['zcml'],))
            from zope.configuration import xmlconfig
            try:
                xmlconfig.file(options['zcml'])
            except Exception, e:
                from traceback import print_tb
                
                print_tb(sys.exc_info()[2])
                raise e
        
        service = MultiService()
        
        jobs = JobService()
        web = internet.TCPServer(int(options["port"]), NevowSite(Root(jobs)))
        
        service.addService(jobs)
        service.addService(web)
        
        return service

serviceMaker = MeercatNevowServiceMaker()
